/*
 * @Description: 登录用户
 * @Author: DHL
 * @Date: 2021-12-31 14:41:21
 * @LastEditors: DHL
 * @LastEditTime: 2024-02-02 14:05:44
 */

import { defineStore } from 'pinia'
import { router } from '@/router'
import {
  apiGetLoginUserCache,
  apiLogin,
  apiLoginRefreshCache,
  apiLoginByToken,
  apiLogOut,
  apiSwitchLoginUserTenant,
  apiLoginByTokenStr
} from '@/api/common/login'
import { LoginUserAppModel, LoginUserModel } from '@/api/common/model/loginModel'
import { store } from '@/store'
import { storageUtils } from '@/utils/storageUtils'
import { resetRouter } from '@/router'
import { useTagsViewStore } from './tagsView'
import { ElMessage } from 'element-plus'
import { merge } from 'lodash-es'
import { isEmpty } from '@/utils/isUtils'
import { usePermissionStore } from './permission'
import { useCacheDataStore } from './cacheData'
import { getUrlParam } from '@/utils/twUtils'

/**
 * 登录用户缓存KEY
 */
const LOGIN_USER_KEY = 'TW-LOGIN-USER'

export interface ILoginUserState extends LoginUserModel {}

const loginUserStore = defineStore({
  id: 'loginUserStore',
  state: (): ILoginUserState => ({
    id: null,
    ip: null,
    loginName: null,
    name: null,
    userType: null,
    devloper: false,
    status: 1,
    firstLogin: 0,
    organizations: null,
    roles: null,
    resources: null,
    avatar: null,
    introduction: null,
    developer: false,
    tenantId: null,
    token: null,
    app: null,
    appList: []
  }),
  getters: {
    appId(state): string {
      if (state.app) {
        return state.app.appId
      }
      return ''
    },
    appToken(state): string {
      if (state.app) {
        return state.app.appToken
      }
      return ''
    },
    appSecret(state): string {
      if (state.app) {
        return state.app.appSecret
      }
      return ''
    },
    appName(state): string {
      if (state.app) {
        return state.app.name
      }
      return ''
    },
    appNum(state): number {
      return state.appList.length
    }
  },
  actions: {
    /**
     * 登录
     * @param loginParams
     * @returns
     */
    login(loginParams: { loginName: string; password: string }) {
      return new Promise((resolve, reject) => {
        apiLogin(loginParams)
          .then((result) => {
            if (result?.success) {
              const loginUser: Nullable<LoginUserModel> = result?.data
              Object.assign(this, loginUser)
              this.searchLoginUser().then((loginUserResult) => {
                resolve(loginUserResult)
              })
            } else {
              ElMessage.error(result?.message)
              resolve(result)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 通过token登录
     * @returns
     */
    loginByToken(token?: string) {
      return new Promise((resolve, reject) => {
        if (isEmpty(token)) {
          apiLoginByToken()
            .then((result) => {
              if (result?.success) {
                const loginUser: Nullable<LoginUserModel> = result?.data
                Object.assign(this, loginUser)
                this.searchLoginUser().then((loginUserResult) => {
                  resolve(loginUserResult)
                })
              } else {
                ElMessage.error(result?.message)
                // 重置缓存登录用户
                this.clearLoginUser()
                resolve(result)
              }
            })
            .catch((error) => {
              reject(error)
            })
        } else {
          apiLoginByTokenStr(token)
            .then((result) => {
              if (result?.success) {
                const loginUser: Nullable<LoginUserModel> = result?.data
                Object.assign(this, loginUser)
                this.searchLoginUser().then((loginUserResult) => {
                  resolve(loginUserResult)
                })
              } else {
                ElMessage.error(result?.message)

                // 重置缓存登录用户
                this.clearLoginUser()

                resolve(result)
              }
            })
            .catch((error) => {
              reject(error)
            })
        }
      })
    },

    /**
     * 查询登录用户信息
     * @returns
     */
    searchLoginUser() {
      return new Promise((resolve, reject) => {
        apiGetLoginUserCache()
          .then((result) => {
            const loginUser: Nullable<LoginUserModel> = result?.data
            this.setLoginUser(loginUser)
            resolve(result)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    /**
     * 刷新缓存
     */
    refreshCache() {
      return new Promise((resolve, reject) => {
        apiLoginRefreshCache()
          .then((result) => {
            const loginUser: Nullable<LoginUserModel> = result?.data
            this.setLoginUser(loginUser)
            resolve(result)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    logOut() {
      apiLogOut()

      // 重置缓存登录用户
      this.clearLoginUser()

      // 重置路由
      resetRouter()
    },

    /**
     * 初始化缓存
     */
    initLoginUserByLocalStorage() {
      if (isEmpty(this.id)) {
        const tokenParams: Nullable<string> = getUrlParam('token')
        if (isEmpty(tokenParams)) {
          const loginUser: ILoginUserState = storageUtils.getLocalItem(LOGIN_USER_KEY)
          this.setLoginUser(loginUser)
        }
      }
    },

    clearLoginUser() {
      this.id = null
      this.ip = null
      this.loginName = null
      this.name = null
      this.userType = null
      this.devloper = false
      this.status = 1
      this.firstLogin = 0
      this.organizations = null
      this.roles = null
      this.resources = null
      this.avatar = null
      this.introduction = null
      this.token = null
      this.app = null
      this.appList = []

      // 删除缓存登录用户
      storageUtils.removeLocalItem(LOGIN_USER_KEY)

      // 重置缓存数据
      useCacheDataStore().clearCacheData()

      // 重置权限
      usePermissionStore().clearPermission()

      // 重置导航页签
      useTagsViewStore().clearView()
    },

    /**
     * 设置登录用户
     * @param loginUser 登录用户
     * @param isBuildCache  是否构建缓存
     */
    setLoginUser(loginUser: Nullable<ILoginUserState>) {
      this.clearLoginUser()

      if (loginUser) {
        merge(this, loginUser)

        storageUtils.setLocalItem({
          key: LOGIN_USER_KEY,
          value: loginUser
        })

        // 构建权限
        usePermissionStore().buildPermission(loginUser.resources)

        // 构建字典缓存
        useCacheDataStore().buildCacheDataAction()
      }
    },

    setFirstlogin() {},

    /**
     * 切换系统
     * @param app
     */
    switchAppAction(app: LoginUserAppModel) {
      this.app = app
      this.searchLoginUser().then((result) => {
        router.push({ path: '/redirect/dashboard' })
      })
    },

    /**
     * 切换租户
     * @param tenantId
     */
    switchTenantAction(tenantId: string) {
      if (isEmpty(tenantId)) {
        return
      }
      apiSwitchLoginUserTenant(tenantId).then((result) => {
        const loginUser: Nullable<LoginUserModel> = result?.data
        this.setLoginUser(loginUser)
        router.push({ path: '/redirect/dashboard' })
      })
    }
  }
})

export function useLoginUserStore() {
  const _loginUserStore = loginUserStore(store)
  _loginUserStore.initLoginUserByLocalStorage()
  return _loginUserStore
}
